package com.itelite.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itelite.common.info.Result;
import static com.itelite.common.util.JwtTokenUtils.*;
import com.itelite.domain.pojo.LoginUser;
import com.itelite.handler.exception.TokenIsExpiredException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 27-06-2021-19:05
 **/
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (release(request.getRequestURI())||tokenHeader == null || !tokenHeader.startsWith(TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        } catch (TokenIsExpiredException e) {
            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String reason = "统一处理，原因：" + e.getMessage();
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.failure(reason)));
            response.getWriter().flush();
            return;
        }
        super.doFilterInternal(request, response, chain);
    }

    private boolean release(String uri) {
        return uri.endsWith("/captcha.jpg") || uri.equals("/login");
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenIsExpiredException {
        String token = tokenHeader.replace(TOKEN_PREFIX, "");
        boolean expiration = false;
        try {
            expiration = isExpiration(token);
        } catch (Exception e) {
            logger.info("解析token出错");
            throw new TokenIsExpiredException("token异常");
        }
        if (expiration) {
            logger.info("token超时了");
            throw new TokenIsExpiredException("token超时了");
        } else {
            HashMap<String,Object> userInfos = getUserInfo(token);
            LoginUser loginUser = LoginUser.builder()
                    .userId((Integer) userInfos.get(USER_ID))
                    .username((String) userInfos.get(USER_NAME))
                    .groupId((Integer) userInfos.get(USER_GROUPID))
                    .realName((String) userInfos.get(USER_REAL_NAME)).build();
            return new UsernamePasswordAuthenticationToken(loginUser, null,
                    Collections.singleton(new SimpleGrantedAuthority((String) userInfos.get(USER_ROLE)))
            );
        }
    }
}
